<template>
  <div>
    <!-- 面包屑 -->
    <el-breadcrumb separator=">">
      <el-breadcrumb-item to="/admin/home">首页</el-breadcrumb-item>
      <el-breadcrumb-item>分类管理</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card class="category-container">
      <!-- 1行3列的布局 -->
      <el-row>
        <el-col :span="10">
          <el-button type="primary" size="mini" icon="el-icon-circle-plus-outline" @click="handleAdd"> 添加分类 </el-button>
        </el-col>
        <el-col :span="8" :offset="6">
          <el-input size="small" placeholder="请输入搜索关键字" prefix-icon="el-icon-search" v-model="searchMsg"></el-input>
          <el-button type="primary" size="mini" @click="searchcategory">搜索</el-button>
        </el-col>
      </el-row>
      <!-- 表格 -->
      <el-table border :data="categories">
        <el-table-column label="id" prop="id"></el-table-column>
        <el-table-column label="分类名称" prop="alias"></el-table-column>
        <el-table-column label="操作">
          <template v-slot:default="categories">
            <el-button size="mini" type="primary" icon="el-icon-edit" @click="handleEdit(categories.row.id)"> 编辑 </el-button>
            <el-button size="mini" type="danger" icon="el-icon-delete" @click="handleDel(categories.row.id)"> 删除 </el-button>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页器 -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="page"
        :page-sizes="[5, 10]"
        :page-size="size"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      ></el-pagination>
    </el-card>
    <el-dialog :title="isEdit ? '修改分类' : '添加分类'" :visible.sync="dialogVisible" width="40%">
      <el-form ref="categoryForm" label-width="80px" :model="categoryForm" :rules="categoryRules">
        <el-form-item label="分类名称" prop="alias">
          <el-input placeholder="请输入分类名称" v-model.trim="categoryForm.alias"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="onSubmit">提交</el-button>
          <el-button @click="cancelAdd">取消</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: 'BackEndMyCategory',
  data() {
    return {
      searchMsg: '',
      categories: [],
      page: 1 /* 当前页 */,
      size: 5 /*  */,
      total: 0 /* 总记录数 */,
      dialogVisible: false,
      categoryForm: {
        alias: ''
      },
      categoryRules: {
        alias: [{ required: true, message: '分类名称不能为空', trigger: 'blur' }]
      },
      isEdit: false
    }
  },
  created() {
    this.getcategories()
  },
  methods: {
    getcategories() {
      this.$http.get(`/categories?page=${this.page}&size=${this.size}`).then(({ code, result, page }) => {
        this.page = Number(page)
        if (code === 0) {
          this.categories = result.data
          this.total = result.total
        }
      })
    },
    handleSizeChange(val) {
      // 记录每页显示多少条记录
      this.size = val
      // 发送请求, 更新数据
      this.getcategories()
    },
    handleCurrentChange(val) {
      // 记录当前的页码
      this.page = val

      // 发送请求
      this.getcategories()
    },
    handleEdit(id) {
      // 显示对话框
      this.dialogVisible = true

      // 更新状态
      this.isEdit = true

      // 根据id发送请求, 获取数据
      this.$http.get(`/categories/${id}`).then(res => {
        this.categoryForm = res.result
      })
    },
    handleAdd() {
      // 显示对话框
      this.dialogVisible = true

      // 更新状态
      this.isEdit = false
    },
    onSubmit() {
      // 获取组件对象
      this.$refs.categoryForm.validate(valid => {
        if (valid) {
          if (this.isEdit) {
            // 修改状态. 发送修改请求
            this.$http
              .put(`/categories/${this.categoryForm.id}`, {
                alias: this.categoryForm.alias
              })
              .then(res => {
                console.log(res)
                if (res.code == 1) {
                  this.$message({
                    type: 'error',
                    message: res.message,
                    duration: 1000
                  })
                  return
                } else {
                  this.$message({
                    type: 'success',
                    message: res.message,
                    duration: 1000
                  })
                }
                this.dialogVisible = false
                // 2. 清空表单
                this.$refs.categoryForm.resetFields()
                // 3. 重新获取数据
                this.getcategories()
              })
          } else {
            // 添加状态. 发送添加请求. 调用接口
            // POST /users {username: 'xxx', password: 'xxx'}
            this.$http.post('/categories', this.categoryForm).then(res => {
              const { code, message } = res
              if (code == 1) {
                this.$message({
                  type: 'error',
                  message: message,
                  duration: 1000
                })
                // this.dialogVisible = false;
                this.$refs.categoryForm.resetFields()
                return
              } else {
                this.$message({
                  type: 'success',
                  message: message,
                  duration: 1000
                })
              }

              // 1. 关闭对话框
              this.dialogVisible = false
              // 2. 清空表单
              this.$refs.categoryForm.resetFields()
              // 3. 重新获取数据
              this.getcategories()
            })
          }
        }
      })
    },
    handleDel(id) {
      this.$http.delete(`/categories/${id}`).then(res => {
        // 提示信息
        this.$message({
          type: 'success',
          message: '删除成功',
          duration: 1000
        })
        // 获取数据
        this.getcategories()
      })
    },
    cancelAdd() {
      this.dialogVisible = false
    },
    async searchcategory() {
      const { result } = await this.$http.get('/categories/search/category', { params: { page: this.page, size: this.size, searchMsg: this.searchMsg } })
      if (result.data.length == 0) {
        this.$message({
          type: 'error',
          message: '没有查询到相关分类',
          duration: 1000
        })
        this.searchMsg = ''
        return
      }
      this.categories = result.data
      this.searchMsg = ''
    }
  }
}
</script>

<style scoped>
.category-container {
  margin-top: 10px;
}
.el-input {
  width: 70%;
  margin-right: 10px;
  margin-bottom: 10px;
}
</style>
